package com.dongdongshop.controller;

import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.pojo.TbContent;
import com.dongdongshop.service.ContentService;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("web")
public class WebController {

    @DubboReference
    private ContentService contentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("getBannerImg")
    @ResponseBody
    public Result getBannerImg(Long categoryId,Integer pageSize,Integer end){
        try{
            String key = "bannerImg" + categoryId;
            ValueOperations valueOperations = redisTemplate.opsForValue();
            String b =(String) valueOperations.get(key);
            if(b!=null){
                List<TbContent> list = new Gson().fromJson(b,new TypeToken<List<TbContent>>(){}.getType());
                return Result.ok().setData(list);
            }else{
                List<TbContent> list = contentService.getBannerImg(categoryId,pageSize,end);
                String s = new Gson().toJson(list);
                valueOperations.set(key,s);
                return Result.ok().setData(list);
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.respones(ResultEnum.ERROR);
        }
    }
}
